package com.luoqiuy.poet.service.iml;

import com.luoqiuy.poet.entity.Content;
import com.luoqiuy.poet.entity.Poet;
import com.luoqiuy.poet.mapper.ContentMapper;
import com.luoqiuy.poet.mapper.PoetMapper;
import com.luoqiuy.poet.mapper.UserMapper;
import com.luoqiuy.poet.service.PoetService;
import com.luoqiuy.poet.service.redisService.impl.RedisServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;

@Service
public class PoetServiceImpl implements PoetService {

    @Autowired
    private PoetMapper poetMapper;
    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisServiceImpl redisService;

    public Logger log = LoggerFactory.getLogger(PoetServiceImpl.class);

    /**
     * 先缓存中查询整体评论，没有则数据库
     * @param request
     * @param poetId
     */
    @Override
    public void poetInfo(HttpServletRequest request, int poetId) {

        HttpSession session = request.getSession();
        //先查找缓存，没有则查询数据库
        Poet poet = redisService.loadCachePoetByPoetId(poetId);
        if (null == poet){
            poet = poetMapper.loadPoetByPoetId(poetId);
            //写入缓存
            boolean res = redisService.writePoetCacheByPoetId(poetId, poet);
            if (!res)
                log.warn("writePoetCacheByPoetId failed "+ poetId);
        }

        if (null == poet)
            log.warn("the poetInfo is null of poetId = " + poetId);

        List<Content> contents ;
        contents = redisService.loadCompleteCacheContentByPoetId(poetId);
        if (null != contents){
            session.setAttribute("poet",poet);
            session.setAttribute("contents",contents);
            return;
        }

        //查询评论缓存
        contents = redisService.loadCacheContentByPoetId(poetId);
        if (null == contents){
            contents = contentMapper.loadContentByPoetId(poetId);
            //写入缓存
            boolean res = redisService.writeContentCacheByPoetId(poetId, contents);
            if (!res)
                log.warn("writeContentCacheByPoetId failed " + poetId);
        }

        contents.forEach(content -> {
            String userImg = userMapper.loadUserImgByUserId(content.getUserId());
            content.setUserImg(userImg);
        });

        boolean cache = redisService.writeCompleteCacheContents(poetId, contents);
        if (!cache)
            log.warn("writeCompleteCacheContents failed "+ poetId);
        session.setAttribute("poet",poet);
        session.setAttribute("contents",contents);
    }

    @Override
    public void updateAm(HttpServletRequest request, int id) {
        HttpSession session = request.getSession();
        Poet p = (Poet)session.getAttribute("poet");
        Optional.ofNullable(p).orElseGet(() -> {
            Poet poet = redisService.loadCachePoetByPoetId(id);
            Optional.ofNullable(poet).orElseGet(() ->{
                Poet po = poetMapper.loadPoetByPoetId(id);
                boolean res = redisService.writePoetCacheByPoetId(id, po);
                if (!res)
                    log.info("writePoetCacheByPoetId failed  in updateAm + " + id + po.getName());
                return po;
            });
            return poet;
        });

    }

    /**
     * 先写缓存，根据缓存的结果再决定是否写入数据库
     * @param request
     * @param poet
     */
    @Override
    @Transactional
    public void updatePm(HttpServletRequest request, Poet poet) {

        HttpSession session = request.getSession();
        Poet p = (Poet)session.getAttribute("poet");
        if (null == poet.getTxt() || poet.getTxt().equals(p.getTxt()))
            return;
        boolean res =  redisService.writePoetCacheByPoetId(p.getId(),poet);
        if (!res)
            log.warn("writePoetCacheByPoetId failed in updatePm " + p.getId());
        poetMapper.writePoetById(p.getId(), poet);
        log.info("writePoetById in updatePm success " + p.getId());

    }
}
